package com.pond.pond.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.pond.common.core.domain.R;
import com.pond.pond.client.DeptClient;
import com.pond.pond.domain.DeptFacilityRelation;
import com.pond.pond.domain.PondComment;
import com.pond.pond.domain.dto.PondDTO;
import com.pond.pond.domain.dto.PondFacilityDTO;
import com.pond.pond.domain.vo.FishingSpotVo;
import com.pond.pond.domain.vo.PondCommentVo;
import com.pond.pond.domain.vo.PondNameOptionsVo;
import com.pond.pond.service.IAppFishingSpotService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.pond.common.log.annotation.Log;
import com.pond.common.log.enums.BusinessType;
import com.pond.common.security.annotation.RequiresPermissions;
import com.pond.pond.domain.Pond;
import com.pond.pond.service.IPondService;
import com.pond.common.core.web.controller.BaseController;
import com.pond.common.core.web.domain.AjaxResult;
import com.pond.common.core.web.page.TableDataInfo;

@RestController
@RequestMapping("/pond")
public class PondController extends BaseController
{
    @Autowired
    private DeptClient deptClient;

    @Autowired
    private IPondService pondService;

    @Autowired
    private IAppFishingSpotService fishingSpotService;

    /**
     * 查询鱼塘名称列表
     */
    @RequiresPermissions("pond:pond:optionList")
    @GetMapping("/pond-options")
    public TableDataInfo list() {
        startPage();
        List<PondNameOptionsVo> list = pondService.selectPondOptionList();
        return getDataTable(list);
    }

    /**
     * 查询鱼塘管理列表（支持多部门权限）
     */
    @RequiresPermissions("pond:pond:list")
    @GetMapping("/list")
    public TableDataInfo list(Pond pond)
    {
        Long deptId = pond.getDeptId();
//
//        if (deptId != null) {
//            // 传了deptId，校验权限，并且用它过滤
//            deptClient.checkDeptDataScope(deptId);
//            pond.setDeptId(deptId);
//        } else {
//            // 不传deptId，查询时不限制部门权限过滤
//            pond.setDeptId(null); // 或不设置
//        }

        // 设置查询条件
        pond.setDeptId(deptId);

        startPage();
        List<Pond> list = pondService.selectPondList(pond);
        List<PondDTO> listDto = list.stream().map(p -> {
            PondDTO dto = new PondDTO();
            BeanUtils.copyProperties(p, dto);

            // fishTypes 字段特殊处理：字符串 → List<String>
            if (p.getFishTypes() != null && !p.getFishTypes().isEmpty()) {
                dto.setFishTypes(Arrays.asList(p.getFishTypes().split(",")));
            } else {
                dto.setFishTypes(Collections.emptyList());
            }

            return dto;
        }).collect(Collectors.toList());

        return getDataTable(listDto);
    }

    /**
     * 获取鱼塘管理详细信息
     */
    @RequiresPermissions("pond:pond:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        Pond pond =  pondService.selectPondById(id);
        PondDTO mypondDTO = new PondDTO();
        BeanUtils.copyProperties(pond, mypondDTO);

        // fishTypes 字段特殊处理：String → List<String>
        if (pond.getFishTypes() != null && !pond.getFishTypes().isEmpty()) {
            mypondDTO.setFishTypes(Arrays.asList(pond.getFishTypes().split(",")));
        } else {
            mypondDTO.setFishTypes(Collections.emptyList());
        }

        return success(mypondDTO);
    }


    /**
     * 新增鱼塘管理，校验用户是否有权限操作指定部门
     */
    @RequiresPermissions("pond:pond:add")
    @Log(title = "鱼塘管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PondDTO pond)
    {
        // 校验当前用户对鱼塘所属部门是否有权限
        if (pond.getDeptId() != null) {
            deptClient.checkDeptDataScope(pond.getDeptId());
        }
        return toAjax(pondService.insertPond(pond));
    }

    /**
     * 修改鱼塘管理，校验用户是否有权限操作指定部门
     */
    @RequiresPermissions("pond:pond:edit")
    @Log(title = "鱼塘管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PondDTO pond)
    {
        deptClient.checkDeptDataScope(pond.getDeptId());
        return toAjax(pondService.updatePond(pond));
    }

    /**
     * 删除鱼塘管理，支持多部门权限校验（如果鱼塘带部门信息）
     */
    @RequiresPermissions("pond:pond:remove")
    @Log(title = "鱼塘管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 可以遍历判断每个鱼塘是否属于当前用户权限部门
        for (Long id : ids) {
            Pond pond = pondService.selectPondById(id);
            if (pond.getDeptId() != null) {
                deptClient.checkDeptDataScope(pond.getDeptId());
            }
        }
        return toAjax(pondService.deletePondByIds(ids));
    }

    /**
     * 更新鱼塘背景图
     */
    @RequiresPermissions("pond:pond:edit")
    @Log(title = "鱼塘背景图", businessType = BusinessType.UPDATE)
    @PutMapping("/update-background")
    public AjaxResult updateBackground(@RequestParam Long pondId, @RequestParam String backgroundUrl) {
        // 查询原始信息，校验权限
        Pond pond = pondService.selectPondById(pondId);
        if (pond == null) {
            return AjaxResult.error("鱼塘不存在");
        }
        if (pond.getDeptId() != null) {
            deptClient.checkDeptDataScope(pond.getDeptId());
        }

        // 更新背景图
        int rows = pondService.updatePondBackground(pondId, backgroundUrl);
        return toAjax(rows);
    }

    /**
     * 评价鱼塘
     */
    @Log(title = "评价鱼塘", businessType = BusinessType.INSERT)
    @PostMapping("/commentPond")
    public AjaxResult commentPond(@RequestBody PondComment pondComment){
        return toAjax(pondService.addCommentPond(pondComment));
    }

    /**
     * 查看鱼塘评价
     */
    @GetMapping("/commentPond")
    public TableDataInfo commentPond(){
        List<PondCommentVo> list = pondService.getCommentPond();
        return  getDataTable(list);
    }

    /**
     * 查看鱼塘评价
     */
    @GetMapping("/commentPondDept")
    public R<List<PondCommentVo>> commentPondByDeptId(@RequestParam Long deptId){
        List<PondCommentVo> list = pondService.getCommentPondByDeptId(deptId);
        if(list!=null&& !list.isEmpty()){
            return  R.ok(list,"获取评价成功");
        }else{
            return R.ok(null,"暂无数据");
        }
    }


    /**
     * 查看鱼塘评价
     */
    @Log(title = "查看鱼塘评价", businessType = BusinessType.INSERT)
    @DeleteMapping("/commentPond/{ids}")
    public AjaxResult commentPond(@PathVariable Long[] ids){
        return  toAjax(pondService.deleteCommentPondByIds(ids));
    }

    /**
     * 修改鱼塘评价
     */
    @PutMapping("/commentPond")
    public AjaxResult updateCommentPond(@RequestBody PondCommentVo pondCommentVo){
        return toAjax(pondService.updateCommentPond(pondCommentVo));
    }

    /**
     * 获取钓场列表（可按坐标距离排序）
     */
    @GetMapping("/listFishingSpots")
    public AjaxResult listFishingSpots(
            @RequestParam(required = false) BigDecimal latitude,
            @RequestParam(required = false) BigDecimal longitude,
            @RequestParam(required = false) String keyword
    ) {
        List<FishingSpotVo> list = fishingSpotService.listFishingSpots(latitude, longitude, keyword);
        return AjaxResult.success(list);
    }

    /**
     * 获取钓场详情信息
     */
    @GetMapping("/getFishingSpotDetail/{id}")
    public AjaxResult getFishingSpotDetail(@PathVariable Long id) {
        FishingSpotVo vo = fishingSpotService.getFishingSpotDetail(id);
        return AjaxResult.success(vo);
    }

    /**
     * 鱼塘新增设施
     */
    @Log(title = "鱼塘新增设施", businessType = BusinessType.INSERT)
    @PostMapping("/addFacility")
    public AjaxResult addFacility(@RequestBody PondFacilityDTO pondFacilityDTO)
    {
        return toAjax(pondService.addFacility(pondFacilityDTO));
    }

    /**
     * 鱼塘设施列表
     */
    @Log(title = "鱼塘设施列表", businessType = BusinessType.INSERT)
    @PostMapping("/getFacility/{id}")
    public R<List<DeptFacilityRelation>> getFacility(@PathVariable("id") Long deptId)
    {
        return R.ok(pondService.getFacility(deptId));
    }
}

